<?php
namespace app\middleware;

use app\pub\Ants4PHP;
use think\facade\Db;

class Pub
{
    public function handle($request, \Closure $next)
    {
        // 获取头部信息
        $appkey = $request->header('appkey');
        $signature = $request->header('signature');
        $uniacid = $request->header('uniacid');  // 微擎绑定的应用ID

        // 查询数据库中的appkey和appsecret
        $cloudSetting = Db::table('ims_zst_marketing_cloud_setting')->where('uniacid', $uniacid)->find();

        if (empty($cloudSetting)) {
            // 就来了
            return redirect('/addons/zst_marketing/inc/web/public/Pub/signErr');
        }

        if ($appkey != $cloudSetting['appkey']) {
            // 就来了
            return redirect('/addons/zst_marketing/inc/web/public/Pub/signErr');
        }

        // 前端传来的所有的值
        $params = $request->param();
        $a = Ants4PHP::ant_ASCII($params);
        $limit=array(" ","　","\t","\n","\r");
        $rep=array("","","","","");
        // 校验
        $b = $a.str_replace($limit,$rep,date("Y-m-d"));
        $sig = hash_hmac('sha256', $b,  $cloudSetting['appsecret']);

        if ($signature != $sig) {
            // 就来了
            return redirect('/addons/zst_marketing/inc/web/public/Pub/signErr');
        }
        return $next($request);

    }
}
